package com.tianpengtech.front.web.task;

import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.kit.Ret;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Model;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.ehcache.CacheKit;
import com.tianpengtech.admin.dictionary.DictionaryDao;
import com.tianpengtech.common.GlobalConfigConstant;
import com.tianpengtech.common.exception.ValidateException;
import com.tianpengtech.common.im.kit.PushKit;
import com.tianpengtech.common.model.authenticate.Authenticate;
import com.tianpengtech.common.model.fair.Fair;
import com.tianpengtech.common.model.task.Task;
import com.tianpengtech.common.model.task.TaskSource;
import com.tianpengtech.common.model.user.User;
import com.tianpengtech.common.util.IpKit;
import com.tianpengtech.common.util.JsonUtil;
import com.tianpengtech.common.util.QiNiuUtil;
import com.tianpengtech.common.util.XxxUtil;
import com.tianpengtech.front.web.common.controller.BaseController;
import com.tianpengtech.front.web.common.interceptor.PassportInterceptor;
import com.tianpengtech.front.web.fair.FairService;
import com.tianpengtech.front.web.login.LoginService;

import javax.persistence.criteria.CriteriaBuilder;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Controller for task management.
 * 
 * @author Delicate
 */
// @Clear(PassportInterceptor.class)
public class TaskWebController extends BaseController {
	private TaskService service = new TaskService();
	private FairService fairService = new FairService();
	private DictionaryDao dictionaryDao = new DictionaryDao();

	public void index() {
		render("task_list.html");
	}

	public void list() {
		int pageNum = getParaToInt(GlobalConfigConstant.PARAM_NAME_PAGENUM, GlobalConfigConstant.DEFAULT_VALUE_PAGENUM);
		int pageSize = getParaToInt(GlobalConfigConstant.PARAM_NAME_PAGESIZE,
				GlobalConfigConstant.DEFAULT_VALUE_PAGESIZE);
		Map<String, Object> params = new HashMap<>();
		params.put("taskName", getPara("taskName"));
		params.put("taskStatus", getPara("status"));
		User user = getAttr(LoginService.loginAccountCacheName);
		params.put("user", user.get(User.ID));
		Page<Task> page = service.task(pageNum, pageSize, params);
		renderJson(page);
	}

	public void form() {
		render("task_add_new.html");
	}

	public void formNew() {
		User user = getAttr(LoginService.loginAccountCacheName);
		if (user == null) {
			renderJson(Ret.fail("msg", "未登录"));
			return;
		}
		Authenticate auth = service.isCreate(user.get(User.ID));

		if (auth == null) {
			redirect("/passport/detail?id=" + user.get(User.ID));
			return;
		} else if (auth.getInt(Authenticate.STATUS) == Authenticate.STATUS_SUCCESS) {
			setAttr("domain", QiNiuUtil.DOMAIN);
			setAttr("priceList", service.getPriceList());
			render("task_add_new.html");
			return;
		} else if (auth.getInt(Authenticate.STATUS) == Authenticate.STATUS_APPROVING) {
			redirect("/passport/detail?id=" + user.get(User.ID));
			return;
		} else if (auth.getInt(Authenticate.STATUS) == Authenticate.STATUS_FAILURE) {
			redirect("/passport/detail?id=" + user.get(User.ID));
			return;
		}
	}

	/**
	 * 任务创建
	 */
	@Before({ Tx.class })
	public void save() {
		try {
			Task task = getModel(Task.class, "task");
			String[] source = getParaValues("source");
			User user = getAttr(LoginService.loginAccountCacheName);
			if (user == null) {
				renderJson(Ret.fail("msg", "未登录"));
				return;
			}
			task.set(Task.CREATE_USER, user.get(User.ID));
			service.save(task, source);
			renderJson(JsonUtil.printObject(task.get(Task.ID)));
		} catch (ValidateException e) {
			renderJson(JsonUtil.printError(e.getMessage()));
		}
	}

	public void dispatcher() {
		int id = getParaToInt("id");
		Task task = Task.dao.findById(id);
		User user = getAttr(LoginService.loginAccountCacheName);
		if (task.getInt(Task.EXTENSION_TYPE) == Task.EXT_TYPE_ZD) {
			// 如果是指定主播， 跳转到选择主播页面
			setAttr("task", task.get(Task.ID));
			forwardAction("/platform/task/choiceFairNew");
		} else {
			// 如果是认领，跳转到创建成功页面
			setAttr("task", task);
			PushKit.pushSystemMessageNow(
					"用户【" + user.getStr(User.MOBILE) + "】发布了任务《" + task.getStr(Task.TASK_TITLE) + "》");
			render("task_success.html");
		}
	}

	/**
	 * 选择网红页面
	 */
	public void changeFair() {

		render("task_wh.html");
	}

	public void choiceFairNew() {
		setAttr("task", getAttr("task"));
		setAttr("region", Db.findByCache(Fair.FAIR_CACHE_NAME, Fair.FAIR_CACHE_REGION,
				"select REGION_ID,REGION_NAME from region where PARENT_ID=1"));
		setAttr("platform", dictionaryDao.readParents(10055));
		setAttr("channel", dictionaryDao.readParents(10056));
		render("task_fair_new.html");
	}

	public void success() {
		render("task_success.html");
	}

	/**
	 * 选择完网红后保存
	 */
	@Before(Tx.class)
	public void saveTaskWait() {
		// String[] fairs=getParaValues("fairs");
		User user = getAttr(LoginService.loginAccountCacheName);
		String fairsStr = getPara("fairs");
		String[] fairs = fairsStr.split(",");
		if (fairs == null || fairs.length == 0) {
			renderJson(Ret.fail("msg", "保存失败，数据不正确"));
			return;
		}
		String task = getPara("task");
		if (StrKit.isBlank(task)) {
			renderJson(Ret.fail("msg", "保存失败，数据不正确"));
			return;
		}
		Ret ret = service.saveTaskWait(fairs, task);
		if (ret.isOk()) {
			Task temp = service.findTaskById(task);
			setAttr("task",temp);
			setAttr("fairs", fairService.findByWhite(task));
			PushKit.pushSystemMessageNow(
					"用户【" + user.getStr(User.MOBILE) + "】发布了任务《" + temp.getStr(Task.TASK_TITLE) + "》");
			render("task_success.html");
		} else {
			renderJson(ret);
		}
	}

	/**
	 * 任务点击数统计
	 */
	@Before(TaskCountValidator.class)
	public void taskCount() {
		String ua = getHeader("User-Agent");
		String ref = getHeader("Referer");
		String ip = IpKit.getRealIp(getRequest());
		String code = getPara("code");
		service.saveTaskClick(ref, ua, ip, code);
		renderText("ok");
	}

	/**
	 * 任务转化数统计
	 */
	@Before(TaskCountValidator.class)
	public void taskCvs() {
		String ua = getHeader("User-Agent");
		String ref = getHeader("Referer");
		String ip = IpKit.getRealIp(getRequest());
		String code = getPara("code");
		service.saveTaskCvs(ref, ua, ip, code);
		renderText("ok");
	}

	public void click() {
		render("click.html");
	}

	/**
	 * 任务详情页
	 */
	public void detail() {
		String id = getPara("id");
		if (StrKit.isBlank(id)) {
			renderJson(Ret.fail());
			return;
		}
		Task task = service.findTaskById(id);
		if (task == null) {
			renderJson(Ret.fail("msg", "任务不存在"));
			return;
		}
		List<Fair> fairs = fairService.findByTask(id);
		if (task.getInt(Task.STATUS).intValue() == Task.STATUS_WAIT) {
			setAttr("task", task.get(Task.ID));
			forwardAction("/platform/task/choiceFairNew");
			return;
		}
		setAttr("task", task);
		setAttr("fairs", fairs);
		renderTemplate("task_detail.html");
	}

	/**
	 * 获取任务资源
	 */
	public void taskSource() {
		String id = getPara("id");
		if (StrKit.isBlank(id)) {
			renderJson(Ret.fail("msg", "任务不存在"));
			return;
		}
		List<TaskSource> source = service.findSourceByTask(Integer.parseInt(id));
		setAttr("sources", source);
		setAttr("id", id);
		render("task_perview.html");
	}

	/**
	 * 保存排序
	 */
	@Before({ TaskSourceValidator.class, Tx.class })
	public void saveTaskSource() {
		String id = getPara("id");
		if (StrKit.isBlank(id)) {
			renderJson(Ret.fail("msg", "任务不存在"));
			return;
		}
		Enumeration<String> names = getParaNames();
		Map<String, String> sources = new HashMap<>();
		while (names.hasMoreElements()) {
			String key = names.nextElement();
			sources.put(key, getPara(key));
		}
		service.saveTaskSource(sources);
		redirect("/platform/task/taskSource?id=" + id);
	}

	
	public void viewH5(){
		
		renderTemplate("h5_preview.html");
	}
	
	public void showH5(){
		
		renderTemplate("showH5.html");
	}
}
